package package_;


import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import szkola_database_entity.SzkolaUser;
import szkola_database_entity.SzkolaWydzial;

public class Klasa_ {

	private static EntityManagerFactory emf;
	private static EntityManager  em;
	
	private static void polaczenie(){
		emf =Persistence.createEntityManagerFactory("jpa_mysql");
		em = emf.createEntityManager();
	}
	public static SzkolaWydzial findwydzial(SzkolaWydzial sz){
		try{
			polaczenie();
		return (SzkolaWydzial) em.createNamedQuery("findByName").setParameter("nazwa",sz.getNazwa()).getSingleResult();
		}
		catch(Exception e){
			return null;
		}
	}
	public static SzkolaUser finduser_(SzkolaUser sz){
		try{
			polaczenie();
		return  (SzkolaUser)em.createNamedQuery("findByMail").setParameter("email",sz.getEmail()).getSingleResult();
		}
		catch(Exception e){
			return null;
		}
	}
	public static int updateUserSession(SzkolaUser sz,String id_session){
		try{
		polaczenie();
		sz.setLoginSesja(id_session);
		SzkolaUser sz_=em.find(SzkolaUser.class, sz.getId());
		em.getTransaction().begin();
		sz_.setId(sz.getId());
		sz_.setLoginSesja(id_session);
		em.getTransaction().commit();
		return 1;
		}
		catch(Exception e){
			return -1;
		}
	}
/*	public static SzkolaUser findUsera(SzkolaUser sz){
		polaczenie();
			try{
				SzkolaUser a= (SzkolaUser) em.createNamedQuery("findByMail").setParameter("email",sz.getEmail()).getSingleResult();
				System.out.println(a.toString());
		    return (SzkolaUser) em.createNamedQuery("findByMail").setParameter("email",sz.getEmail()).getSingleResult();
			}
			catch(Exception e){
				return null;
			}
	}*/
	public static String getRolaIfExist(SzkolaUser sz){
		try{
			return ((SzkolaUser) em.createNamedQuery("findByMail").setParameter("email",sz.getEmail()).getSingleResult()).getRola();
		}
		catch(Exception e){
			return null;
		}
	}
	/*public static void dodaj(SzkolaUser sz){
		emf =Persistence.createEntityManagerFactory("database");
		em = emf.createEntityManager();
		em.getTransaction().begin();
		em.persist(sz);
		em.getTransaction().commit();
		System.out.println("dodano");
	}
	public static void dodajea(SzkolaUser sz){
		emf =Persistence.createEntityManagerFactory("databaseea");
		em = emf.createEntityManager();
		em.getTransaction().begin();
		em.persist(sz);
		em.getTransaction().commit();
		System.out.println("dodano");
	}*/
	
}
